package io.renren.modules.aic.service.impl;

import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.Query;
import io.renren.modules.aic.dao.MemberMachineDao;
import io.renren.modules.aic.dao.TeamDao;
import io.renren.modules.aic.entity.MachineEntity;
import io.renren.modules.aic.entity.MemberEntity;
import io.renren.modules.aic.entity.MemberMachineEntity;
import io.renren.modules.aic.entity.TeamDto;
import io.renren.modules.aic.entity.TeamEntity;
import io.renren.modules.aic.service.MachineService;
import io.renren.modules.aic.service.MemberMachineService;
import io.renren.modules.aic.service.MemberService;
import io.renren.modules.aic.service.TeamService;
import io.renren.modules.sys.service.SysConfigService;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("teamService")
public class TeamServiceImpl extends ServiceImpl<TeamDao, TeamEntity> implements TeamService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	SysConfigService sysConfigService;

	@Autowired
	TeamDao teamDao;

	@Autowired
	MemberService memberService;

	@Autowired
	MemberMachineDao memberMachineDao;

	@Autowired
	MachineService machineService;

	@Autowired
	MemberMachineService memberMachineService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Page<TeamEntity> page = this.selectPage(new Query<TeamEntity>(params).getPage(), new EntityWrapper<TeamEntity>());

		return new PageUtils(page);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateUserLevel() {
		logger.info("updateUserLevel execute");
		MemberEntity memberEntity = null;
		Date now = new Date();
		// 普通矿工升级一级矿工
		List<TeamDto> teamList = teamDao.countTeamByUserLevel(ProjectConstant.USER_LEVEL_NORMAL);
		if (CollectionUtils.isNotEmpty(teamList)) {
			for (TeamDto teamDto : teamList) {

				memberEntity = memberService.selectById(teamDto.getHigherOne());

				// 是否达到升级标准
				if (teamDto.getCount() >= sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_ONE)) {

					// 已经是更高等级，无需升级
					if (memberEntity.getUserLevel() >= ProjectConstant.USER_LEVEL_ONE) {
						continue;
					}
					// 更新等级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_ONE);
					memberService.updateById(memberEntity);
				} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_ONE) {
					// 降级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_NORMAL);
					userLevelDown(memberEntity);// 递归降级检查
					memberService.updateById(memberEntity);
				}
			}
		}

		// 一级矿工升二级矿工或降级
		teamList = teamDao.countTeamByUserLevel(ProjectConstant.USER_LEVEL_ONE);
		if (CollectionUtils.isNotEmpty(teamList)) {
			for (TeamDto teamDto : teamList) {

				memberEntity = memberService.selectById(teamDto.getHigherOne());

				// 是否达到升级标准
				if (teamDto.getCount() >= sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_TWO)) {

					// 已经是更高等级，无需升级
					if (memberEntity.getUserLevel() >= ProjectConstant.USER_LEVEL_TWO) {
						continue;
					}
					// 更新等级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_TWO);
					memberService.updateById(memberEntity);

				} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_TWO) {
					// 降级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_ONE);
					userLevelDown(memberEntity);// 递归降级检查
					memberService.updateById(memberEntity);
				}
			}
		}

		// 二级矿工升三级矿工或降级
		teamList = teamDao.countTeamByUserLevel(ProjectConstant.USER_LEVEL_TWO);
		if (CollectionUtils.isNotEmpty(teamList)) {
			for (TeamDto teamDto : teamList) {

				memberEntity = memberService.selectById(teamDto.getHigherOne());

				// 是否达到升级标准
				if (teamDto.getCount() >= sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_THREE)) {

					// 已经是更高等级，无需升级
					if (memberEntity.getUserLevel() >= ProjectConstant.USER_LEVEL_THREE) {
						continue;
					}
					// 更新等级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_THREE);
					memberService.updateById(memberEntity);

					// 赠送矿机
					userLevelChangeGiveMachine(teamDto.getHigherOne(), ProjectConstant.MACHINE_TYPE_LARGE);
				} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_THREE) {
					// 降级
					memberEntity = new MemberEntity();
					memberEntity.setId(teamDto.getHigherOne());
					memberEntity.setUpdateTime(now);
					memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_TWO);
					userLevelDown(memberEntity);// 递归降级检查
					memberService.updateById(memberEntity);
				}
			}

			// 三级矿工升四级矿工或降级
			teamList = teamDao.countTeamByUserLevel(ProjectConstant.USER_LEVEL_THREE);
			if (CollectionUtils.isNotEmpty(teamList)) {
				for (TeamDto teamDto : teamList) {

					memberEntity = memberService.selectById(teamDto.getHigherOne());

					// 是否达到升级标准
					if (teamDto.getCount() >= sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_FOUR)) {

						// 已经是更高等级，无需升级
						if (memberEntity.getUserLevel() >= ProjectConstant.USER_LEVEL_FOUR) {
							continue;
						}
						// 更新等级
						memberEntity = new MemberEntity();
						memberEntity.setId(teamDto.getHigherOne());
						memberEntity.setUpdateTime(now);
						memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_FOUR);
						memberService.updateById(memberEntity);

						// 赠送矿机
						userLevelChangeGiveMachine(teamDto.getHigherOne(), ProjectConstant.MACHINE_TYPE_HUGE);
					} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_FOUR) {
						// 降级
						memberEntity = new MemberEntity();
						memberEntity.setId(teamDto.getHigherOne());
						memberEntity.setUpdateTime(now);
						memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_THREE);
						userLevelDown(memberEntity);// 递归降级检查
						memberService.updateById(memberEntity);
					}
				}
			}

			// 四级矿工检查
			List<MemberEntity> memberList = memberService.selectList(new EntityWrapper<MemberEntity>().eq("user_level", ProjectConstant.USER_LEVEL_FOUR));
			if (CollectionUtils.isNotEmpty(memberList)) {
				for (MemberEntity memberEntity2 : memberList) {
					userLevelDown(memberEntity2);// 递归降级检查
					if (memberEntity2.getUserLevel() != ProjectConstant.USER_LEVEL_FOUR) {
						memberEntity = new MemberEntity();
						memberEntity.setId(memberEntity2.getId());
						memberEntity.setUpdateTime(now);
						memberEntity.setUserLevel(memberEntity2.getUserLevel());
						memberService.updateById(memberEntity);
					}
				}
			}
		}
	}

	/**
	 * 矿工降级
	 * 
	 * @param memberEntity
	 * @return
	 */
	private MemberEntity userLevelDown(MemberEntity memberEntity) {
		Integer temp = null;
		if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_NORMAL) {
			Double t = memberMachineDao.totalHashSecond(memberEntity.getId());
			if (t == null || t < sysConfigService.getValueD(ConfigConstant.MINER_LIMIT_NORMAL)) {
				memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_INITIAL);
			}
		} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_ONE) {
			temp = teamDao.countTeamByHigherOne(ProjectConstant.USER_LEVEL_NORMAL, memberEntity.getId());
			if (temp == null || temp < sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_ONE)) {
				memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_NORMAL);
				userLevelDown(memberEntity);
			}
		} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_TWO) {
			temp = teamDao.countTeamByHigherOne(ProjectConstant.USER_LEVEL_ONE, memberEntity.getId());
			if (temp == null || temp < sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_TWO)) {
				memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_ONE);
				userLevelDown(memberEntity);
			}
		} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_THREE) {
			temp = teamDao.countTeamByHigherOne(ProjectConstant.USER_LEVEL_TWO, memberEntity.getId());
			if (temp == null || temp < sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_THREE)) {
				memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_TWO);
				userLevelDown(memberEntity);
			}
		} else if (memberEntity.getUserLevel() == ProjectConstant.USER_LEVEL_FOUR) {
			temp = teamDao.countTeamByHigherOne(ProjectConstant.USER_LEVEL_THREE, memberEntity.getId());
			if (temp == null || temp < sysConfigService.getValueI(ConfigConstant.MINER_LIMIT_FOUR)) {
				memberEntity.setUserLevel(ProjectConstant.USER_LEVEL_THREE);
				userLevelDown(memberEntity);
			}
		}
		return memberEntity;
	}

	/**
	 * 会员等级升级赠送矿机
	 * 
	 * @param memberId
	 * @param machineType
	 */
	private void userLevelChangeGiveMachine(Long memberId, int machineType) {

		Integer c = memberMachineDao.selectCount(new EntityWrapper<MemberMachineEntity>().eq("member_id", memberId).eq("is_reward", ProjectConstant.COMMON_YES)
				.eq("machine_type", machineType));
		if (c == null || c == 0) {
			logger.info("会员等级升级系统自动[memberId:%s]", memberId);
			MachineEntity machine = machineService
					.selectOne(new EntityWrapper<MachineEntity>().eq("machine_type", machineType).eq("status", ProjectConstant.MACHINE_STATUS_ENABLE));
			if (machine == null) {
				logger.info("会员等级升级系统自动赠送矿机失败[memberId:%s]", memberId);
			} else {
				MemberMachineEntity mm = new MemberMachineEntity();
				mm.setMemberId(memberId);
				mm.setMachineNo("M" + DateUtils.format(new Date(), "yyyyMMddHH") + RandomStringUtils.randomNumeric(5));
				mm.setMachineName(machine.getMachineName());
				mm.setMachineType(machine.getMachineType());
				mm.setPrice(machine.getPrice());
				mm.setHashSecond(machine.getHashSecond());
				mm.setTotalDays(machine.getTotalDays());
				mm.setTotalProfit(machine.getTotalProfit());
				mm.setDayProfit(machine.getDayProfit());
				mm.setRunningDays(0);
				mm.setSumProfit(0d);
				mm.setPreProfit(0d);
				mm.setStatus(ProjectConstant.MACHINE_RUNSTATUS_RUNNING);
				mm.setIsReward(ProjectConstant.COMMON_YES);
				mm.setCreateTime(new Date());
				mm.setMachineImg(machine.getMachineImg());
				memberMachineService.insert(mm);
			}
		}
	}
}
